package com.qf.security1.service;

import com.qf.security1.mapper.UserMapper;
import com.qf.security1.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 当security在进行登录时，会通过这个对象的loadUserByUsername方法根据页面传递过来的username查询数据库中的用户信息
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     *
     * @param username  页面传递过来的username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据username去查询数据库 (user是我们自己根据数据库表结构创建的)
        User user = userMapper.findByUsername(username);

        if (user != null){
            //查询当前用户具备的角色
            List<String> roleNames = userMapper.findRoleNamesByUsername(username);
            String[] roles = null;
            if(roleNames==null||roleNames.size()==0){
                roles = new String[]{"DEFAULT"};
            }else{
                roles = roleNames.toArray(new String[0]);
            }

            //返回一个security的user
            return org.springframework.security.core.userdetails.User
                    .withUsername(username)
                    //从数据库查询到的密码（可能是明文，也可能是密文.取决于之前注册用户时是否对密码进行过加密处理）
                    .password(user.getPassword())

                    //表示当前登录用户的权限。和authorities二选一 ,当我们的权限字符串不是以ROLE_开头时使用
                    .roles(roles)
                    //表示当前登录用户的权限。和roles二选一，当我们的权限字符串是以ROLE_开头时使用
//                    .authorities("ROLE_P1")
                    .build();
        }

        return null;
    }
}
